package com.lzx.reggie.controller

import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.lzx.reggie.common.BaseContext
import com.lzx.reggie.common.R
import com.lzx.reggie.entity.ShoppingCart
import com.lzx.reggie.service.ShoppingCartService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import java.time.LocalDateTime


/**
 * 购物车
 */

@RestController
@RequestMapping("/shoppingCart")
class ShoppingCartController {

    companion object {
        private val log = LoggerFactory.getLogger(ShoppingCartController::class.java)
    }

    @Autowired
    private lateinit var shoppingCartService: ShoppingCartService

    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    fun add(@RequestBody shoppingCart: ShoppingCart): R<ShoppingCart> {
        log.info("购物车数据:{}", shoppingCart)

        //设置用户id，指定当前是哪个用户的购物车数据
        val currentId = BaseContext.currentId
        shoppingCart.userId = currentId

        val dishId = shoppingCart.dishId

        //查询当前菜品或者套餐是否在购物车中
        //SQL:select * from shopping_cart where user_id = ? and dish_id/setmeal_id = ?
        val cartServiceOne = shoppingCartService.getOne(
            KtQueryWrapper(ShoppingCart::class.java).apply {
                eq(ShoppingCart::userId, currentId)
                if (dishId != null) {
                    //添加到购物车的是菜品
                    eq(ShoppingCart::dishId, dishId)
                } else {
                    //添加到购物车的是套餐
                    eq(ShoppingCart::setmealId, shoppingCart.setmealId)
                }
            })

        if (cartServiceOne != null) {
            //如果已经存在，就在原来数量基础上加一
            cartServiceOne.number = cartServiceOne.number!! + 1
            shoppingCartService.updateById(cartServiceOne)
        } else {
            //如果不存在，则添加到购物车，数量默认就是一
            shoppingCart.number = 1
            shoppingCart.createTime = LocalDateTime.now()
            shoppingCartService.save(shoppingCart)
        }
        return R.success(shoppingCart)
    }

    /**
     * 查看购物车
     * @return
     */
    @GetMapping("/list")
    fun list(): R<List<ShoppingCart>> {
        log.info("查看购物车...")

        return R.success(
            shoppingCartService.list(
                KtQueryWrapper(ShoppingCart::class.java).apply {
                    eq(ShoppingCart::userId, BaseContext.currentId)
                    orderByAsc(ShoppingCart::createTime)
                })
        )
    }

    /**
     * 清空购物车
     * @return
     */
    @DeleteMapping("/clean")
    fun clean(): R<String> {
        shoppingCartService.remove(
            KtQueryWrapper(ShoppingCart::class.java).apply {
                eq(ShoppingCart::userId, BaseContext.currentId)
            })
        return R.success("清空购物车成功")
    }
}